package thread;

import java.util.concurrent.*;

/**
 * @Author: hmm
 * @Created: 2019/11/13
 * @Description: Semaphore 信号量得使用
 *        现实场景，停车场显示有否还有车位
 * @Modified by:
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        Semaphore semaphore = new Semaphore(100);

        for (int i = 0; i < 100; i++) {
            final int no = i;
            pool.execute(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("获取进入许可的车牌号：" + no);
                    //车辆停留时间
                    Thread.sleep(3000);

                    semaphore.release();
                    System.out.println("车牌号：" + no + "离开停车场");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        pool.shutdown();

    }
}
